#coding:utf8
#
# Author: CMGS
# Created on 2011-1-20
#

from libs.sqlpool import tinyPool as _pool
from utils.shorturl import encode_url as _encode
TABLE_NAME = 'url'

def add(url):
    sqlCmd = '''INSERT INTO `%s`(`url`) VALUES ('%s');''' % (TABLE_NAME, url)
    ret = _pool.execute(sqlCmd)
    if ret != 1:
        return False
    tinyUrl = _genTinyUrlById(url)
    return setTinyUrl(url, tinyUrl), tinyUrl

def setTinyUrl(url, tinyUrl):
    sqlCmd = '''UPDATE `%s` SET `tiny`='%s' WHERE `url`='%s';''' 
    sqlCmd = sqlCmd % (TABLE_NAME, tinyUrl, url)
    ret = _pool.execute(sqlCmd)
    if ret != 1:
        return False
    return True

def delete(url):
    sqlCmd = '''DELETE FROM %s WHERE url = '%s';''' % (TABLE_NAME, url)
    ret = _pool.execute(sqlCmd)
    if ret != 1:
        return False
    return True

def getTinyUrl(url):
    sqlCmd = '''SELECT tiny FROM %s WHERE url = '%s';''' % (TABLE_NAME, url)
    ret = _pool.query(sqlCmd, _pool.RET_DICT_ROW_FOR_KEY)
    if not len(ret) > 0:
        return None
    return ret[0]['tiny']

def _genTinyUrlById(url):
    sqlCmd = '''SELECT id FROM %s WHERE url = '%s';''' % (TABLE_NAME, url)
    ret = _pool.query(sqlCmd, _pool.RET_DICT_ROW_FOR_KEY)
    if not len(ret) > 0:
        return False
    id = int(ret[0]['id'])
    tinyUrl = _encode(id)
    return tinyUrl

if __name__ == '__main__':
    print add('http://www.verycd.com/sto/feed')
    print getTinyUrl('http://www.verycd.com/sto/feed')
    print setTinyUrl('http://www.verycd.com/sto/feed', 'EmJ')
    print getTinyUrl('http://www.verycd.com/sto/feed')
    print delete('http://www.verycd.com/sto/feed')
